import React, { Component } from 'react';

import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import Dialog from 'material-ui/Dialog';
import { GridList, GridTile } from 'material-ui/GridList';

import { getHotelInfoAPI, postForFreeAPI, getHotelSecretAPI, getHotelOrdersAPI, getSecretOperateAPI } from '../../services/API.js';
import R from 'ramda';
import async from 'async';

import store from '../../stores/main';

import Waiting from '../Waiting';
import Alert from '../Alert';

export default class Home extends Component {

    componentDidMount () {
      this.setState(store.dispatch({type:'OPEN_WAITING'}));
      getHotelInfoAPI({},(res, err)=> {
        if (err) {
          this.setState(store.dispatch({type:'OPEN_ALERT', re:err}));
        } else {
          if(res.statusNo == 200) {
            this.setState(store.dispatch({type:'GET_HOTEL_INFO', data: res.data}));
          } else {
            this.setState(store.dispatch({type:'OPEN_ALERT', re: res.msg}));
          }
        }
      });
    }

    getInfo () {
      this.setState(store.dispatch({type:'OPEN_WAITING'}));
      getHotelInfoAPI({
        pageNo: 1,
        searchKey: store.getState().searchKey
      },(res, err)=> {
        if (err) {
          this.setState(store.dispatch({type:'OPEN_ALERT', re:err}));
        } else {
          if(res.statusNo == 200) {
            this.setState(store.dispatch({type:'GET_HOTEL_INFO', data: res.data}));
          } else {
            this.setState(store.dispatch({type:'OPEN_ALERT', re: res.msg}));
          }
        }
      });
    }

    getOrdersInfo (next, pageNo) {
      this.setState(store.dispatch({type:'OPEN_WAITING'}));
      getHotelOrdersAPI({
        hotelId: store.getState().hotelId,
        pageNo: pageNo || 1
      }, (res, err) => {
        if (err) {
          this.setState(store.dispatch({type:'OPEN_ALERT', re: err}));
        } else {
          if(res.statusNo == 200) {
            this.setState(store.dispatch({type:'GET_ORDERS_INFO', data: res.data}));
            if (next) next(null);
          } else {
            this.setState(store.dispatch({type:'OPEN_ALERT', re: res.msg}));
          }
        }
      });
    }

    getSecretsInfo (next) {
      this.setState(store.dispatch({type:'OPEN_WAITING'}));
      getHotelSecretAPI({
        hotelId: store.getState().hotelId
      }, (res, err) => {
        if (err) {
          this.setState(store.dispatch({type:'OPEN_ALERT', re:err}));
        } else {
          if(res.statusNo == 200) {
            this.setState(store.dispatch({type:'GET_SECRET_INFO', data: res.data}));
            if (next) next(null);
          } else {
            this.setState(store.dispatch({type:'OPEN_ALERT', re: res.msg}));
          }
        }
      });
    }

    constructor(props) {
        super(props);
        this.state = {
            open: false,
            openDialog: false,
            hotel: {}
        }
    }

    openToggle (value, e) {
      this.setState({open: !this.state.open, hotel: value});
      this.setState(store.dispatch({type:'SET_HOTEL_ID', data: value.hotelId}));
      async.series({
        secrets: (next) => {
          this.getSecretsInfo(next);
        } ,
        orders: (next) => {
          this.getOrdersInfo(next);
        }

      });

    };

    getOrdersByPage (pageNo, e) {
      this.setState(store.dispatch({type:'OPEN_WAITING'}));
      this.getOrdersInfo(null, pageNo);
    }

    setSearchKey (e, value) {
      this.setState(store.dispatch({type: 'SET_SEARCH_KEY', data: value}));
    }

    getHotelByPage (pageNo, e) {
      getHotelInfoAPI({
        pageNo: pageNo,
        searchKey: store.getState().searchKey
      },(res, err)=> {
        if (err) {
          this.setState(store.dispatch({type:'OPEN_ALERT', re:err}));
        } else {
          if(res.statusNo == 200) {
            this.setState(store.dispatch({type:'GET_HOTEL_INFO', data: res.data}));
          } else {
            this.setState(store.dispatch({type:'OPEN_ALERT', re: res.msg}));
          }
        }
      });
    }

    getHotelBySearchKey () {
      this.getInfo();
    }

    vipForFree (value, e)  {
      this.setState(store.dispatch({type: 'SET_DOG_NO', data: value}));
      this.setState({openDialog: true});
      e.stopPropagation();
    };

    closeVipFree () {
      this.setState({openDialog: false});
    };

    setFreeMonth (e, value) {
      this.setState(store.dispatch({type: 'SET_FREE_MONTH', data: value}));
    }

    sendSecretActive (secretNo, sta, e) {
      sta = sta == 'T' ? 'F' : 'T';
      getSecretOperateAPI({
        secretNo: secretNo,
        sta: sta
      }, (res, err) => {
        if (err) {
          this.setState(store.dispatch({type:'OPEN_ALERT', re:err}));
        } else {
          if (res.statusNo == 200) {
            this.getSecretsInfo();
          } else {
            this.setState(store.dispatch({type:'OPEN_ALERT', re: res.msg}));
          }
        }
      });
    }

    sendVipFree () {
      postForFreeAPI({
        dogNo: store.getState().dogNo,
        months: store.getState().monthFree
      },(err, res) => {
        if (err) {
          this.setState(store.dispatch({type:'OPEN_ALERT', re:err}));
        } else {
          if (res.statusNo == 200) {
            this.closeVipFree();
            this.setState(store.dispatch({type:'OPEN_ALERT', re: '会员延期成功!'}));
            this.getInfo();
          } else {
            this.setState(store.dispatch({type:'OPEN_ALERT', re: res.msg}));
          }
        }
      });

    }

    render() {

        let rootState = store.getState();
        var pages = R.defaultTo([])(rootState.pages);
        var hotels = R.defaultTo([])(rootState.hotels);
        var secrets = R.defaultTo([])(rootState.secretList);
        var orders = R.defaultTo([])(rootState.orderList);
        var orderPages = R.defaultTo([])(rootState.orderPages);

        const pageBtnStyle = {
          marginRight: 20,
          width: 45,
          minWidth: 45
        };
        const rowHover = {
          cursor: 'pointer'
        };

        const pageStyle = {
          textAlign: 'center',
          position: 'fixed',
          bottom: 50
        };
        const actions = [
          <RaisedButton
            label="延期"
            primary={true}
            style={{marginRight: 20}}
            onTouchTap={this.sendVipFree.bind(this)}
            />,
          <FlatButton
            label="取消"
            primary={true}
            keyboardFocused={true}
            onTouchTap={this.closeVipFree.bind(this)}
            />

        ];

        return (
            <div>
                <div>
                  <TextField hintText="关键字" onChange={this.setSearchKey.bind(this)}/>
                  <RaisedButton label="搜索" primary={true} style={{marginLeft: 30}} onTouchTap={this.getHotelBySearchKey.bind(this)}/>
                </div>
                <Table>
                    <TableHeader displaySelectAll={false} adjustForCheckbox={false}>
                        <TableRow>
                            <TableHeaderColumn >酒店ID</TableHeaderColumn>
                            <TableHeaderColumn >代理商</TableHeaderColumn>
                            <TableHeaderColumn >所属集团</TableHeaderColumn>
                            <TableHeaderColumn >有效截止日期</TableHeaderColumn>
                            <TableHeaderColumn >加密狗号</TableHeaderColumn>
                            <TableHeaderColumn >酒店名称</TableHeaderColumn>
                            <TableHeaderColumn >序列号个数</TableHeaderColumn>
                            <TableHeaderColumn >创建时间</TableHeaderColumn>
                            <TableHeaderColumn >状态</TableHeaderColumn>
                            <TableHeaderColumn>操作</TableHeaderColumn>
                        </TableRow>
                    </TableHeader>
                    <TableBody displayRowCheckbox={false} showRowHover={true}>
                      {
                        hotels.map((hotel, ind) => {
                          return (
                            <TableRow onTouchTap={this.openToggle.bind(this, hotel)} style={rowHover} key={ind}>
                              <TableRowColumn >{hotel.hotelId}</TableRowColumn>
                              <TableRowColumn >{hotel.dealerName}</TableRowColumn>
                              <TableRowColumn >{hotel.companyName}</TableRowColumn>
                              <TableRowColumn >{hotel.endDate}</TableRowColumn>
                              <TableRowColumn >{hotel.dogNo}</TableRowColumn>
                              <TableRowColumn >{hotel.hotelName}</TableRowColumn>
                              <TableRowColumn >{hotel.validSecret}</TableRowColumn>
                              <TableRowColumn >{hotel.createTime}</TableRowColumn>
                              <TableRowColumn >{hotel.bzSta}</TableRowColumn>
                              <TableRowColumn >
                                <RaisedButton label="会员延期" primary={true} onTouchTap={this.vipForFree.bind(this, hotel.dogNo)}/>
                              </TableRowColumn>
                            </TableRow>
                          )
                        })
                      }
                    </TableBody>
                </Table>
                <div style={pageStyle}>
                  {
                    pages.map((val, ind)=>{
                      if(val == rootState.pageNo){
                        return (
                          <RaisedButton key={ind} label={val} primary={true} style={pageBtnStyle}/>
                        )
                      }else {
                        return (
                          <FlatButton key={ind} label={val} primary={true} style={pageBtnStyle} onTouchTap={this.getHotelByPage.bind(this, val)}/>
                        )
                      }
                    })
                  }
                </div>
                <Dialog
                  title="会员延期"
                  actions={actions}
                  modal={false}
                  open={this.state.openDialog}
                  onRequestClose={this.closeVipFree.bind(this)}
                  contentStyle={{width: 350}}
                  >
                  <TextField hintText="延期月数" onChange={this.setFreeMonth.bind(this)}/> <br/>
                </Dialog>
                <Drawer
                    docked={false}
                    width={950}
                    open={this.state.open}
                    onRequestChange={(open) => this.setState({open})}
                    containerStyle={{overflowX: 'hidden'}}
                    >
                    <Table>
                      <TableHeader displaySelectAll={false} adjustForCheckbox={false}>
                        <TableRow>
                          <TableHeaderColumn>代理商</TableHeaderColumn>
                          <TableHeaderColumn>所属集团</TableHeaderColumn>
                          <TableHeaderColumn>有效截止日期</TableHeaderColumn>
                          <TableHeaderColumn>创建时间</TableHeaderColumn>
                        </TableRow>
                      </TableHeader>
                      <TableBody displayRowCheckbox={false} showRowHover={true}>
                        <TableRow>
                          <TableRowColumn >{this.state.hotel.dealerName}</TableRowColumn>
                          <TableRowColumn >{this.state.hotel.companyName}</TableRowColumn>
                          <TableRowColumn >{this.state.hotel.endDate}</TableRowColumn>
                          <TableRowColumn >{this.state.hotel.createTime}</TableRowColumn>
                        </TableRow>
                      </TableBody>
                    </Table>
                    <h3 style={{marginLeft: 22}}>序列号</h3>
                    <GridList style={{display: 'flex', flexWrap: 'nowrap', height: 30}}>
                      {
                        secrets.map((val)=> (
                          <div style={{height: 30}}>{val.secretNo}</div>
                        ))
                      }
                    </GridList>
                    <Table>
                      <TableHeader displaySelectAll={false} adjustForCheckbox={false}>
                        <TableRow>
                          <TableHeaderColumn style={{width: '70px'}}>序列号</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '10px'}}>用户姓名</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '80px'}}>激活时间</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '20px'}}>类别</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '5px'}}>操作</TableHeaderColumn>
                        </TableRow>
                      </TableHeader>
                      <TableBody displayRowCheckbox={false} showRowHover={true}>
                        {
                          secrets.map((val, ind) => {
                            var btn = '';
                            if (val.sta == 'T') {
                              btn = (<RaisedButton label="停用" onTouchTap={this.sendSecretActive.bind(this, val.secretNo, val.sta)}/>);
                            } else {
                              btn = (<RaisedButton label="启用" primary={true} onTouchTap={this.sendSecretActive.bind(this, val.secretNo, val.sta)}/>);
                            }
                            return (
                              <TableRow key={ind}>
                                <TableRowColumn style={{width: '70px'}}>{val.secretNo}</TableRowColumn>
                                <TableRowColumn style={{width: '10px'}}>{val.userName}</TableRowColumn>
                                <TableRowColumn style={{width: '80px'}}>{val.startTime}</TableRowColumn>
                                <TableRowColumn style={{width: '20px'}}>{val.secretType}</TableRowColumn>
                                <TableRowColumn style={{width: '5px'}}>
                                  {btn}
                                </TableRowColumn>
                              </TableRow>
                            )
                          })
                        }
                      </TableBody>
                    </Table>
                    <h3 style={{marginLeft: 22}}>订单</h3>
                    <Table>
                      <TableHeader displaySelectAll={false} adjustForCheckbox={false}>
                        <TableRow>
                          <TableHeaderColumn style={{width: '10px'}}>订单ID</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '10px'}}>总金额</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '20px'}}>类别</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '50px'}}>交易状态</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '10px'}}>操作人</TableHeaderColumn>
                          <TableHeaderColumn style={{width: '60px'}}>创建时间</TableHeaderColumn>
                        </TableRow>
                      </TableHeader>
                      <TableBody displayRowCheckbox={false} showRowHover={true}>
                        {
                          orders.map((val, ind) => {
                            return (
                              <TableRow key={ind}>
                                <TableRowColumn style={{width: '10px'}}>{val.recId}</TableRowColumn>
                                <TableRowColumn style={{width: '10px'}}>{val.totalFee}</TableRowColumn>
                                <TableRowColumn style={{width: '20px'}}>{val.operateType}</TableRowColumn>
                                <TableRowColumn style={{width: '50px'}}>{val.status}</TableRowColumn>
                                <TableRowColumn style={{width: '10px'}}>{val.operator}</TableRowColumn>
                                <TableRowColumn style={{width: '60px'}}>{val.createTime}</TableRowColumn>
                              </TableRow>
                            )
                          })
                        }
                      </TableBody>
                    </Table>
                    <div style={{textAlign: 'center', marginBottom: 20}}>
                      {
                        orderPages.map((val, ind)=>{
                          if(val == rootState.orderPageNo){
                            return (
                              <RaisedButton key={ind} label={val} primary={true} style={pageBtnStyle}/>
                            )
                          }else {
                            return (
                              <FlatButton key={ind} label={val} primary={true} style={pageBtnStyle} onTouchTap={this.getOrdersByPage.bind(this, val)}/>
                            )
                          }
                        })
                      }
                    </div>
                </Drawer>
                <Waiting />
                <Alert />
            </div>
        )
    }
}
